﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;
using FERROU8API.Pub;

namespace FERROU8API.Plugin
{
    public static class HttpHelper
    {
        public static string PostDataToServer(string ip, string js)
        {
            return PostHttpHelper.PostHttp(ip, js, "application/json", 30000);
        }

        public static string PostDataToServerform(string ip, string js)
        {
            return PostHttpHelper.PostHttp(ip, js, "application/x-www-form-urlencoded", 30000);
        }

        public static string PostDataToServerDic(string ip, Dictionary<string, string> dic, string contenttype)
        {
            return PostHttpHelper.PostHttp(ip, dic, contenttype);
        }
    }


    public class PostHttpHelper
    {
        //body是要传递的参数,格式"roleId=1&uid=2"
        //post的cotentType填写:
        //"application/x-www-form-urlencoded"
        //soap填写:"text/xml; charset=utf-8"
        //timeout 填写超时毫秒
        public static string PostHttp(string url, string body, string contentType, int timeout)
        {
            string responseContent = String.Empty;
            //body = ConvertHelper.GetHtmlEncode(body);
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            try
            {


                httpWebRequest.ContentType = contentType;
                httpWebRequest.Method = "POST";
                httpWebRequest.Timeout = timeout;
                httpWebRequest.ServicePoint.Expect100Continue = false;
                httpWebRequest.ServicePoint.ConnectionLimit = 500;
                DebugWriteLog.WriteLine("URL LOG", "LOG", url + body);
                byte[] btBodys = Encoding.UTF8.GetBytes(body);
                httpWebRequest.ContentLength = btBodys.Length;
                httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {


                    Stream responseStream = httpWebResponse.GetResponseStream();

                    if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                        responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                        responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    Encoding encoding;
                    //if (httpWebResponse.CharacterSet.ToUpper().Contains("ISO-8859-1"))
                    //    encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                    //else
                    encoding = Encoding.UTF8;
                    //encoding = Encoding.GetEncoding("GBK");
                    StreamReader streamReader;
                    streamReader = new StreamReader(responseStream, encoding, true);
                    String resultstr = streamReader.ReadToEnd();

                    resultstr = System.Web.HttpUtility.UrlDecode(resultstr);
                    responseContent = resultstr;

                    httpWebResponse.Close();
                    streamReader.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                httpWebRequest.Abort();
            }
            

            return responseContent;
        }


        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string PostHttp(string url, Dictionary<string, string> dic, string contenttype)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = contenttype;
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }

            DebugWriteLog.WriteLine("URL LOG", "LOG", url + builder.ToString());

            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
        public static string GetHttp(string url, string body, string contentType, int timeout)
        {
            if (!string.IsNullOrEmpty(body))
            {
                url = url + "?" + body;
            }
            //body = ConvertHelper.GetHtmlEncode(body);
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);


            httpWebRequest.ContentType = contentType;
            httpWebRequest.Method = "GET";
            httpWebRequest.Timeout = timeout;

            //byte[] btBodys = Encoding.UTF8.GetBytes(body);
            //httpWebRequest.ContentLength = btBodys.Length;
            //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            Stream responseStream = httpWebResponse.GetResponseStream();

            if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
            else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            String resultstr = streamReader.ReadToEnd();
            string responseContent = resultstr;
            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();

            return responseContent;
        }
    }
}
